package com.axend.lib_base.utils

import android.content.Context
import android.media.MediaPlayer
import android.net.Uri

/**
 * @description音频播放器
 * @author admins
 * @time 2024/7/4 14:11
 */
class AudioPlayer private constructor(private val context: Context) {

    private var mediaPlayer: MediaPlayer? = null

    private fun setAudioResource(resourceId: Int) {
        mediaPlayer?.release()
        mediaPlayer = MediaPlayer.create(context, resourceId)
    }

    private fun setAudioResource(uri: Uri) {
        mediaPlayer?.release()
        mediaPlayer = MediaPlayer().apply {
            setDataSource(context, uri)
            prepare() // You might want to use prepareAsync() in real-world scenarios
        }
    }

    fun play(resourceId: Int) {
        if (mediaPlayer?.isPlaying == true) return
        setAudioResource(resourceId)
        mediaPlayer?.isLooping = true
        mediaPlayer?.start()
    }

    fun play(uri: Uri) {
        setAudioResource(uri)
        mediaPlayer?.start()
    }

    fun pause() {
        mediaPlayer?.pause()
    }

    fun stop() {
        mediaPlayer?.apply {
            if (isPlaying) {
                stop()
            }
//            reset()
            release()
            mediaPlayer = null
        }
    }

    companion object {
        @Volatile
        private var INSTANCE: AudioPlayer? = null

        fun getInstance(context: Context): AudioPlayer =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: AudioPlayer(context).also { INSTANCE = it }
            }
    }
}